package com.lu.dao;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String Driver;
    private static String url;
    private static String user;
    private static String password;

    static {
        Properties properties = new Properties();
        String configFile = "database.properties";
        try {
            InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
            properties.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        user = properties.getProperty("user");
        password = properties.getProperty("password");
    }

    // 创建链接
    public Connection getCon() {
        Connection con = null;
        try {
            Class.forName(Driver);
            con = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }

    //@Test
    public void testGetCon() {
        Assertions.assertNotNull(getCon());
    }

    // 关闭所有对象
    public void closeAll(Connection con, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 通用增删改
    public int executeUpdate(String sql, Object[] parma) {
        int result = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            if (parma != null) {
                for (int i = 0; i < parma.length; i++) {
                    pstmt.setObject(i+1,parma[i]);
                }
            }
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,null);
        }

        return result;
    }
}
